﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DormMS.Common;
using DormMS.IService;
using DormMS.IService.Common;
using DormMS.Model;
using DormMS.Model.SearchModels;
using DormMS.Service;
using Infrastructure;
using NLog;

namespace DormMS.Controllers
{
    public class RoomController : BaseController
    {
        protected IRoomService roomService;
        protected ILogService logService;
        protected IUserInfoService userInfoService;
        protected IBuildingService buildingService;
        protected ISysCodeService sysCodeService;
        protected IStudentBedService studentBedService;
        protected IBedService bedService;
        private static Logger NLog = LogManager.GetLogger("Request");
        /// <summary>
        /// 初期化
        /// </summary>
        /// <param name="s"></param>
        /// <param name="_roomService"></param>
        /// <param name="l"></param>
        /// <param name="_buildingService"></param>
        /// <param name="_sysCodeService"></param>
        /// <param name="_studentBedService"></param>
        public RoomController(IUserInfoService s, IRoomService _roomService, ILogService l, IBuildingService _buildingService, ISysCodeService _sysCodeService, IStudentBedService _studentBedService, IBedService _bedservice) : base(s)
        {
            roomService = _roomService;
            logService = l;
            userInfoService = s;
            buildingService = _buildingService;
            sysCodeService = _sysCodeService;
            studentBedService = _studentBedService;
            bedService = _bedservice;
        }

        /// <summary>
        /// 获取公寓列表
        /// </summary>
        /// <returns></returns>
        // GET: Room
        public ActionResult RoomList()
        {
            return View();
        }

        /// <summary>
        /// 获取公寓初期化列表
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetRoomList(RoomSearchModel search)
        {
            int total = 0;
            var list = roomService.GetRoomList(search, ref total);
            return Json(new { Total = total, Results = list, _UserInfo = userInfoService.GetUserInfo(CurrentLoginUser.Id) });
        }

        /// <summary>
        /// 获取公寓明细
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult RoomDetail()
        {
            return View();
        }

        /// <summary>
        /// 获取公寓明细初期化数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult GetRoomInitDetail(int id)
        {
            var room = roomService.GetRoomInfoById(id);
            if(room == null)
            {
                room = new Room();
                room.RoomNO = "";
            }
            return Json(new { RoomInfo = room, RoomTypeList = roomService.GetRoomType(), RoomAttrList = roomService.GetRoomAttr(), BuildingInfoList = buildingService.GetBuildingInfoList("1 = 1") });
        }
        /// <summary>
        /// 公寓保存CHECK
        /// </summary>
        /// <param name="RoomNO"></param>
        /// <param name="BuildingID"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RoomCheck(string RoomNO, string BuildingId)
        {

            Result result = new Result();
            var entity = roomService.GetRoomInfoByNOAndBuildingID(RoomNO, BuildingId);

            if (entity == null)
            {
                result.isSuccess = true;
            }
            return Json(result);
        }

        /// <summary>
        /// 新增修改公寓信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RoomSave(Room model)
        {
            Result result = new Result();
            try
            {

                var entity = roomService.GetRoomInfoById(model.Id);
                int rstcount = 0;
                if (entity == null)
                {
                    model.AddUserId = CurrentLoginUser.Id;
                    model.AddTime = DateTime.Now;
                    rstcount = roomService.RoomAdd(model);
                    result.isSuccess = true;

                }
                else
                {
                    entity.RoomNO = model.RoomNO;
                    entity.BuildingId = model.BuildingId;
                    entity.RoomAttr = model.RoomAttr;
                    entity.RoomType = model.RoomType;
                    entity.EditUserId = CurrentLoginUser.Id;
                    entity.EditTime = DateTime.Now;
                    rstcount = roomService.RoomEdit(model);
                    result.isSuccess = true;

                }
                
            }
            catch (Exception ex)
            {
                result.msg = "保存公寓信息失败！";
                NLog.Debug("保存公寓信息失败：" + ex.Message + "，" + ex.StackTrace);
            }
            return Json(result);
        }

        /// <summary>
        /// 删除公寓信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RoomDel(Room model)
        {
            Result result = new Result();
            var entity = roomService.GetRoomInfoById(model.Id);

            if (entity != null)
            {
                model.IsDeleted = true;
                roomService.RoomDel(model);
                result.isSuccess = true;
            }
            else
            {
                result.msg = "公寓信息不存在！";
            }
            return Json(result);
        }

        /// <summary>
        /// 导入excel数据
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public ActionResult UpLoadProcess(HttpPostedFileBase file)
        {
            string fileName = System.IO.Path.GetFileName(file.FileName);
            string filePhysicalPath = Server.MapPath("~/Import/" + fileName);
            string pic = "", error = "";
            bool result = false;
            List<string> errorstr = new List<string>();
            
            string[] fields = new string[4];
            try
            {
                //1.保存文件
                file.SaveAs(filePhysicalPath);
                pic = "/Import/" + fileName;
                //2.文件导入
                ExcelHelper excelHelper = new ExcelHelper(filePhysicalPath);
                //DataTable dt = excelHelper.ExportExcelToDataTable(1);

                fields[0] = "BuildingNO";
                fields[1] = "RoomNO";
                fields[2] = "RoomAttrName";
                fields[3] = "RoomTypeName";

                var list = excelHelper.ExcelToList<RoomImport>(fields, 0);
                //3.判断文件导入内容是否正确
                int count = 1;
                int flag = 0;
                List<Room> roomList = new List<Room>();
                foreach(var item in list)
                {
                    var building = buildingService.GetBuildingInfoByNO(item.BuildingNO);
                    if (building == null)
                    {
                        flag = 1;
                        error = "第" + count + "行大楼号不存在！";
                        errorstr.Add(error);
                        break;
                    }
                               
                    if (string.IsNullOrEmpty(item.RoomNO) == true)
                    {
                        flag = 1;
                        error = "第" + count + "行公寓号不能为空！";
                        errorstr.Add(error);
                        break;
                    }

                    var model = roomService.GetRoomInfoByNOAndBuildingID(item.RoomNO, building.Id.ToString());
                    if(model != null)
                    {
                        continue;
                    }

                    count++;

                    Room room = new Room();
                    room.BuildingId = building.Id;
                    
                    
                    room.RoomNO = item.RoomNO;
                    if (string.IsNullOrEmpty(item.RoomAttrName) == false)
                    {
                        var data = sysCodeService.GetSysCodeByCodeNameAndCodeType("公寓性质", item.RoomAttrName);
                        if(data != null)
                        {
                            room.RoomAttr = data.Code;
                        }
                        else
                        {
                            room.RoomAttr = 0;
                        }
                        
                    }
                    else
                    {
                        room.RoomAttr = 0;
                    }

                    if (string.IsNullOrEmpty(item.RoomTypeName) == false)
                    {
                        var data = sysCodeService.GetSysCodeByCodeNameAndCodeType("公寓类型", item.RoomAttrName);
                        if (data != null)
                        {
                            room.RoomType = data.Code;
                        }
                        else
                        {
                            room.RoomType = 0;
                        }
                    }
                    else
                    {
                        room.RoomType = 0;
                    }
                    room.AddTime = DateTime.Now;
                    room.AddUserId = CurrentLoginUser.Id;
                    roomList.Add(room);
                }
                //4.导入进去
                if (flag == 0)
                {
                    roomService.RoomAddImport(roomList);
                    result = true;
                }
                
                if (System.IO.File.Exists(filePhysicalPath))//判断文件是否存在  
                {
                    System.IO.File.Delete(filePhysicalPath);//执行IO文件删除视频,需引入命名空间System.IO;  
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
            }

            return Json(new
            {
                errorstr = errorstr,
                error = error,
                result = result
            });
        }

        /// <summary>
        /// 获取公寓对应学生床位信息列表
        /// </summary>
        /// <returns></returns>
        public ActionResult RoomStudentList()
        {
            return View();
        }
        /// <summary>
        /// 获取公寓对应学生床位初期化信息
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public ActionResult GetRoomStudentInitList(StudentBedSearchModel search)
        {
            int total = 0;
            var list = studentBedService.GetStudentBedBySearch(search , ref total);
            return Json(new { Total = total, Results = list, _UserInfo = userInfoService.GetUserInfo(CurrentLoginUser.Id) } );
        }
    }
}